/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.cpit.platform.common.excel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

import com.cpit.platform.common.excel.annotation.ExcelField;
import com.cpit.platform.common.utils.Encodes;
import com.cpit.platform.common.utils.Reflections;
import com.cpit.platform.log.LogOperator;
import com.google.common.collect.Lists;

/**
 * 导出Excel文件（导出“XLSX”格式，支持大数据量导出 @see org.apache.poi.ss.SpreadsheetVersion）
 * 
 * @author ThinkGem
 * @version 2013-04-21
 * 
 */

public class ExportExcel {
	private static final String LOGGER_NAME = ExportExcel.class.getName();
	// 工作薄对象
	private SXSSFWorkbook wb;

	// 工作表对象
	private Sheet sheet;

	// 样式列表
	private Map<String, CellStyle> styles;

	// 当前行号
	private int rownum;

	// sheet头
	private String title;

	// 表头
	private List<String> headerList;


	private  String datePattern="yyyy-MM-dd HH:mm:ss";

	private Map<String, ExcelField4Map> excelField4MapMap = new HashMap<>();
	private List<ExcelField4Map> excelField4MapList = new ArrayList<>();

	// 注解列表（Object[]{ ExcelField, Field/Method }）
	List<Object[]> annotationList = Lists.newArrayList();
	// 枚举值映射
	Map<ExcelField, Map<Integer, String>> enumMap = new HashMap<ExcelField, Map<Integer, String>>();

	// 转换器映射
	Map<ExcelField, Convertor> convertorMap = new HashMap<ExcelField, Convertor>();

	//数字格式
    Map<ExcelField, String>     decimalFormatMap = new HashMap<>();
	/**
	 * @param title
	 *            表格标题，传“空值”，表示无标题
	 * @param cls
	 *            实体对象，通过annotation.ExportField获取标题
	 */
	public ExportExcel(String title, Class<?> cls) {
		this(title, cls, 1);
	}

	/**
	 * @param title
	 *            表格标题，传“空值”，表示无标题
	 * @param cls
	 *            实体对象，通过annotation.ExportField获取标题
	 */
	public ExportExcel(String title, Class<?> cls, String sheetName) {
		this(title, cls, 1, false, sheetName);
	}

	/**
	 * 
	 * @param title
	 *            表格标题，传“空值”，表示无标题
	 * @param cls
	 *            实体对象，通过annotation.ExportField获取标题
	 * @param includeParentClass
	 *            是否包括父类
	 */
	public ExportExcel(String title, Class<?> cls, boolean includeParentClass) {
		this(title, cls, 1, includeParentClass, "export");
	}

	/**
	 * @param title
	 *            表格标题，传“空值”，表示无标题
	 * @param cls
	 *            实体对象，通过annotation.ExportField获取标题
	 * @param type
	 *            导出类型（1:导出数据；2：导出模板）
	 * @param includeParentClass
	 *            是否包括父类 add by zhuhuayan For Fault Export
	 */
	public ExportExcel(String title, Class<?> cls, int type, boolean includeParentClass) {
		this(title, cls, type, includeParentClass, "export");
	}

	/**
	 * @param title
	 *            表格标题，传“空值”，表示无标题
	 * @param cls
	 *            实体对象，通过annotation.ExportField获取标题
	 * @param type
	 *            导出类型（1:导出数据；2：导出模板）
	 * @param includeParentClass
	 *            是否包括父类
	 * @param sheetName
	 *            sheet名称 add by zhuhuayan For Fault Export
	 */
	public ExportExcel(String title, Class<?> cls, int type, boolean includeParentClass, String sheetName) {
		Field[] fs = cls.getDeclaredFields();

		for (Field f : fs) {
			ExcelField ef = f.getAnnotation(ExcelField.class);
			if (ef != null && (ef.type() == 0 || ef.type() == type)) {
				if (ef.fieldType() != null) {
					Field[] fs_pro = ef.fieldType().getDeclaredFields();
					for (Field f1 : fs_pro) {
						ExcelField ef1 = f1.getAnnotation(ExcelField.class);
						if (ef1 != null && (ef1.type() == 0 || ef1.type() == type)) {

							annotationList.add(new Object[] { ef1, f1 });

							parseEnumDefinition(ef1);
							parseConvertorDefinition(ef1);
						}
					}
				} else {
					annotationList.add(new Object[] { ef, f });

					parseEnumDefinition(ef);
					parseConvertorDefinition(ef);
				}
			}
		}
		if (includeParentClass) {
			Field[] fs_parent = cls.getSuperclass().getDeclaredFields();
			for (Field f : fs_parent) {
				ExcelField ef = f.getAnnotation(ExcelField.class);
				if (ef != null && (ef.type() == 0 || ef.type() == type)) {
					annotationList.add(new Object[] { ef, f });

					parseEnumDefinition(ef);
					parseConvertorDefinition(ef);
				}
			}
		}

		// Get annotation method
		Method[] ms = cls.getDeclaredMethods();
		for (Method m : ms) {
			ExcelField ef = m.getAnnotation(ExcelField.class);
			if (ef != null && (ef.type() == 0 || ef.type() == type)) {
				if (ef.fieldType() != null) {
					Method[] ms_pro = ef.fieldType().getDeclaredMethods();
					for (Method m1 : ms_pro) {
						ExcelField ef1 = m1.getAnnotation(ExcelField.class);
						if (ef1 != null && (ef1.type() == 0 || ef1.type() == type)) {
							annotationList.add(new Object[] { ef1, m1 });

							parseEnumDefinition(ef1);
							parseConvertorDefinition(ef);
						}
					}
				} else {
					annotationList.add(new Object[] { ef, m });
					parseEnumDefinition(ef);
					parseConvertorDefinition(ef);
				}
			}
		}
		if (includeParentClass) {
			Method[] ms_parent = cls.getSuperclass().getDeclaredMethods();
			for (Method m : ms_parent) {
				ExcelField ef = m.getAnnotation(ExcelField.class);
				if (ef != null && (ef.type() == 0 || ef.type() == type)) {
					annotationList.add(new Object[] { ef, m });

					parseEnumDefinition(ef);
					parseConvertorDefinition(ef);
				}
			}
		}

		Collections.sort(annotationList, new Comparator<Object[]>() {
			public int compare(Object[] o1, Object[] o2) {
				return new Integer(((ExcelField) o1[0]).sort()).compareTo(new Integer(((ExcelField) o2[0]).sort()));
			};
		});

		// Initialize
		List<String> headerList = Lists.newArrayList();
		for (Object[] os : annotationList) {
			String t = ((ExcelField) os[0]).title();
			// 如果是导出，则去掉注释
			if (type == 1) {
				String[] ss = StringUtils.split(t, "**", 2);
				if (ss.length == 2) {
					t = ss[0];
				}
			}
			headerList.add(t);
		}
		initialize(title, headerList, sheetName);
	}

	/**
	 * @param title
	 *            表格标题，传“空值”，表示无标题
	 * @param cls
	 *            实体对象，通过annotation.ExportField获取标题
	 * @param type
	 *            导出类型（1:导出数据；2：导出模板）
	 * @param groups
	 *            导入分组
	 */
	public ExportExcel(String title, Class<?> cls, int type, int... groups) {
		this(title, cls, type, "export", groups);
	}

	/**
	 * @param title
	 *            表格标题，传“空值”，表示无标题
	 * @param cls
	 *            实体对象，通过annotation.ExportField获取标题
	 * @param type
	 *            导出类型（1:导出数据；2：导出模板）
	 * @param groups
	 *            导入分组
	 */
	public ExportExcel(String title, Class<?> cls, int type, String sheetName, int... groups) {
		Field[] fs = cls.getDeclaredFields();
		for (Field f : fs) {
			ExcelField ef = f.getAnnotation(ExcelField.class);
			if (ef != null && (ef.type() == 0 || ef.type() == type)) {
				if (groups != null && groups.length > 0) {
					boolean inGroup = false;
					for (int g : groups) {
						if (inGroup) {
							break;
						}
						for (int efg : ef.groups()) {
							if (g == efg) {
								inGroup = true;
								annotationList.add(new Object[] { ef, f });
								break;
							}
						}
					}
				} else {
					annotationList.add(new Object[] { ef, f });
				}
				parseEnumDefinition(ef);
				parseConvertorDefinition(ef);
			}
		}

		// Get annotation method
		Method[] ms = cls.getDeclaredMethods();

		for (Method m : ms) {
			ExcelField ef = m.getAnnotation(ExcelField.class);
			if (ef != null && (ef.type() == 0 || ef.type() == type)) {
				if (groups != null && groups.length > 0) {
					boolean inGroup = false;
					for (int g : groups) {
						if (inGroup) {
							break;
						}
						for (int efg : ef.groups()) {
							if (g == efg) {
								inGroup = true;
								annotationList.add(new Object[] { ef, m });
								break;
							}
						}
					}
				} else {
					annotationList.add(new Object[] { ef, m });
				}
				parseEnumDefinition(ef);
				parseConvertorDefinition(ef);
				parseDecimalFormatDefinition(ef);
			}
		}
		Collections.sort(annotationList, new Comparator<Object[]>() {
			public int compare(Object[] o1, Object[] o2) {
				return new Integer(((ExcelField) o1[0]).sort()).compareTo(new Integer(((ExcelField) o2[0]).sort()));
			};
		});

		// Initialize
		List<String> headerList = Lists.newArrayList();
		for (Object[] os : annotationList) {
			String t = ((ExcelField) os[0]).title();
			// 如果是导出，则去掉注释
			if (type == 1) {
				String[] ss = StringUtils.split(t, "**", 2);
				if (ss.length == 2) {
					t = ss[0];
				}
			}
			headerList.add(t);
		}
		initialize(title, headerList, sheetName);
	}

	private void parseConvertorDefinition(ExcelField ef) {
		String strConvertor = ef.convertor();
		if (!strConvertor.isEmpty()) {
			Convertor convertor = null;
			try {
				convertor = (Convertor) Class.forName(strConvertor).newInstance();
				convertorMap.put(ef, convertor);
			} catch (Exception ex) {
				LogOperator.info(LOGGER_NAME, ex.toString());
			}
		}
	}

	private void parseEnumDefinition(ExcelField ef) {
		String enums = ef.enums();
		if (!enums.isEmpty()) {
			// 去掉首尾的{}，并按,分解
			String[] items = enums.substring(1, enums.length() - 1).split(",");
			Map<Integer, String> map = new HashMap<Integer, String>(items.length);
			for (String item : items) {
				int idx = item.indexOf("=");
				String key = item.substring(0, idx);
				String value;
				// 去掉首尾的"
				value = item.substring(idx + 2, item.length() - 1);
				map.put(Integer.valueOf(key), value);
			}
			enumMap.put(ef, map);
		}
	}
	private  void parseDecimalFormatDefinition(ExcelField ef){
		String decimalFormat = ef.decimalFormat();
		if(!decimalFormat.isEmpty()){
			decimalFormatMap.put(ef,decimalFormat);
		}
	}

	/**
	 * @param title
	 *            表格标题，传“空值”，表示无标题
	 * @param headers
	 *            表头数组
	 */
	public ExportExcel(String title, String[] headers) {
		initialize(title, Lists.newArrayList(headers), "export");
	}

	/**
	 * @param title
	 *            表格标题，传“空值”，表示无标题
	 * @param headers
	 *            表头数组
	 * @param sheetName
	 *            sheetName
	 */
	public ExportExcel(String title, String[] headers,String sheetName) {
		initialize(title, Lists.newArrayList(headers), sheetName);
	}

	/**
	 * @param title
	 *            表格标题，传“空值”，表示无标题
	 * @param headerList
	 *            表头列表
	 */
	public ExportExcel(String title, List<String> headerList) {
		initialize(title, headerList, "export");
	}

	/**
	 * @param title
	 *            表格标题，传“空值”，表示无标题
	 * @param headerList
	 *            表头列表
	 */
	private void initialize(String title, List<String> headerList, String sheetName) {
		this.wb = new SXSSFWorkbook(500);
		this.styles = createStyles(wb);
		this.title = title;
		this.headerList = headerList;
		createSheet(sheetName);
	}

	public void createSheet(String sheetName) {
		this.sheet = wb.createSheet(sheetName);
		// Create title
		if (StringUtils.isNotBlank(title)) {
			Row titleRow = sheet.createRow(rownum++);
			titleRow.setHeightInPoints(30);
			Cell titleCell = titleRow.createCell(0);
			titleCell.setCellStyle(styles.get("title"));
			titleCell.setCellValue(title);
			sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(),
					headerList.size() - 1));
		}

		// Create header
		if (headerList == null) {
			throw new RuntimeException("headerList not null!");
		}
		Row headerRow = sheet.createRow(rownum++);
		headerRow.setHeightInPoints(16);
		for (int i = 0; i < headerList.size(); i++) {
			Cell cell = headerRow.createCell(i);
			cell.setCellStyle(styles.get("header"));
			String[] ss = StringUtils.split(headerList.get(i), "**", 2);
			if (ss.length == 2) {
				cell.setCellValue(ss[0]);
				Comment comment = this.sheet.createDrawingPatriarch()
						.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
				comment.setString(new XSSFRichTextString(ss[1]));
				cell.setCellComment(comment);
			} else {
				cell.setCellValue(headerList.get(i));
			}
			sheet.autoSizeColumn(i);
		}
		for (int i = 0; i < headerList.size(); i++) {
			int colWidth = sheet.getColumnWidth(i) * 2;
			sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
		}
		LogOperator.debug(LOGGER_NAME, "Initialize success.");
	}

	public SXSSFWorkbook getWb() {
		return wb;
	}

	public void setWb(SXSSFWorkbook wb) {
		this.wb = wb;
	}

	public Sheet getSheet() {
		return sheet;
	}

	public void setSheet(Sheet sheet) {
		this.sheet = sheet;
	}

	public Map<String, CellStyle> getStyles() {
		return styles;
	}

	public void setStyles(Map<String, CellStyle> styles) {
		this.styles = styles;
	}

	public int getRownum() {
		return rownum;
	}

	public void setRownum(int rownum) {
		this.rownum = rownum;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public List<String> getHeaderList() {
		return headerList;
	}

	public void setHeaderList(List<String> headerList) {
		this.headerList = headerList;
	}

	public List<Object[]> getAnnotationList() {
		return annotationList;
	}

	public void setAnnotationList(List<Object[]> annotationList) {
		this.annotationList = annotationList;
	}

	public Map<ExcelField, Map<Integer, String>> getEnumMap() {
		return enumMap;
	}

	public void setEnumMap(Map<ExcelField, Map<Integer, String>> enumMap) {
		this.enumMap = enumMap;
	}

	/**
	 * 创建表格样式
	 * 
	 * @param wb
	 *            工作薄对象
	 * @return 样式列表
	 */
	private Map<String, CellStyle> createStyles(Workbook wb) {
		Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
		CellStyle style = wb.createCellStyle();
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		Font titleFont = wb.createFont();
		titleFont.setFontName("Arial");
		titleFont.setFontHeightInPoints((short) 16);
		titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
		style.setFont(titleFont);
		styles.put("title", style);
		style = wb.createCellStyle();
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		style.setBorderRight(CellStyle.BORDER_THIN);
		style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
		style.setBorderLeft(CellStyle.BORDER_THIN);
		style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
		style.setBorderTop(CellStyle.BORDER_THIN);
		style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
		style.setBorderBottom(CellStyle.BORDER_THIN);
		style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
		Font dataFont = wb.createFont();
		dataFont.setFontName("Arial");
		dataFont.setFontHeightInPoints((short) 10);
		style.setFont(dataFont);
		styles.put("data", style);
		addStyleFormat(styles, style, "data");
		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
		style.setAlignment(CellStyle.ALIGN_LEFT);
		styles.put("data1", style);
		addStyleFormat(styles, style, "data1");
		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
		style.setAlignment(CellStyle.ALIGN_CENTER);
		styles.put("data2", style);
		addStyleFormat(styles, style, "data2");
		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
		style.setAlignment(CellStyle.ALIGN_RIGHT);
		styles.put("data3", style);
		addStyleFormat(styles, style, "data3");
		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));

		// style.setWrapText(true);

		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		Font headerFont = wb.createFont();
		headerFont.setFontName("Arial");
		headerFont.setFontHeightInPoints((short) 10);
		headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
		headerFont.setColor(IndexedColors.WHITE.getIndex());
		style.setFont(headerFont);
		styles.put("header", style);
		return styles;
	}

	private void addStyleFormat(Map<String, CellStyle> styles, CellStyle style, String name) {
		CellStyle style0 = wb.createCellStyle();
		style0.cloneStyleFrom(style);
		style0.setDataFormat((short) Cell.CELL_TYPE_NUMERIC);
		styles.put(name + "_0", style0);

		CellStyle style1 = wb.createCellStyle();
		style1.cloneStyleFrom(style);
		style1.setDataFormat((short) Cell.CELL_TYPE_STRING);
		styles.put(name + "_1", style1);

		CellStyle style3 = wb.createCellStyle();
		style3.cloneStyleFrom(style);
		style3.setDataFormat((short) Cell.CELL_TYPE_BLANK);
		styles.put(name + "_3", style3);

		CellStyle style7 = wb.createCellStyle();
		style7.cloneStyleFrom(style);

		style7.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
		styles.put(name + "_7", style7);
	}

	/**
	 * 添加一行
	 * 
	 * @return 行对象
	 */
	public Row addRow() {
		return sheet.createRow(rownum++);
	}

	/**
	 * 添加一个单元格
	 * 
	 * @param row
	 *            添加的行
	 * @param column
	 *            添加列号
	 * @param val
	 *            添加值
	 * @return 单元格对象
	 * 
	 */
	public Cell addCell(Row row, int column, Object val) {
		return this.addCell(row, column, val, 0, Class.class, null,null);
	}

	/**
	 * 添加一个单元格
	 * 
	 * @param row
	 *            添加的行
	 * @param column
	 *            添加列号
	 * @param val
	 *            添加值
	 * @param align
	 *            对齐方式（1：靠左；2：居中；3：靠右）
	 * @param enums
	 *            枚举值映射
	 * @return 单元格对象
	 */
	public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType, Map<Integer, String> enums, String decimalFormat) {
		Cell cell = row.createCell(column);
		String styleBase = "data" + (align >= 1 && align <= 3 ? align : "");
		CellStyle style = styles.get(styleBase);
		;
		try {
			if (val == null) {
				style = styles.get(styleBase + "_" + Cell.CELL_TYPE_BLANK);
				cell.setCellValue("");
			} else if (val instanceof String) {
				style = styles.get(styleBase + "_" + Cell.CELL_TYPE_STRING);
				cell.setCellValue((String) val);
				if (val.toString().contains("\n")) {
					// 单元格格式，自动换行
					style.setWrapText(true);
				}
			} else if (val instanceof Integer || val instanceof Long) {
				// 有枚举值，显示枚举值，否则显示数字
				boolean hasEnum = false;
				if (enums != null) {
					String display = enums.get(((Number) val).intValue());
					if (display != null) {
						style = styles.get(styleBase + "_" + Cell.CELL_TYPE_STRING);
						cell.setCellValue(display);
						hasEnum = true;
					}
				}
				if (!hasEnum) {
					style = styles.get(styleBase + "_" + Cell.CELL_TYPE_NUMERIC);
					cell.setCellValue(((Number) val).doubleValue());
				}
				// } else if (val instanceof Long) {
				// style.setDataFormat((short) Cell.CELL_TYPE_NUMERIC);
				// cell.setCellValue((Long) val);
			} else if (val instanceof Double) {
				style = styles.get(styleBase + "_7");
				if(!decimalFormat.isEmpty()){
					DecimalFormat df = new DecimalFormat(decimalFormat);
					cell.setCellValue(df.format( val));
				}else{
					cell.setCellValue((Double) val);
				}

			} else if (val instanceof Float) {
				style = styles.get(styleBase + "_7");
				if(!decimalFormat.isEmpty()){
					DecimalFormat df = new DecimalFormat(decimalFormat);
					cell.setCellValue(df.format( val));
				}else {
					cell.setCellValue((Float) val);
				}
			} else if (val instanceof Date) {
				String date = DateFormatUtils.format((Date) val, getDatePattern());
				style = styles.get(styleBase + "_" + Cell.CELL_TYPE_STRING);
				cell.setCellValue((String) date);
			} else if (val instanceof Boolean) {
				// 有枚举值，显示枚举值，否则显示true/false
				style = styles.get(styleBase + "_" + Cell.CELL_TYPE_STRING);
				boolean hasEnum = false;
				Integer intVal = ((Boolean) val) ? 1 : 0;
				if (enums != null) {
					String display = enums.get(intVal);
					if (display != null) {
						cell.setCellValue(display);
						hasEnum = true;
					}
				}
				if (!hasEnum) {
					cell.setCellValue(val.toString());
				}
			} else {
				if (fieldType != Class.class) {
					cell.setCellValue((String) fieldType.getMethod("setValue", Object.class).invoke(null, val));
				} else {
					cell.setCellValue((String) Class
							.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
									"fieldtype." + val.getClass().getSimpleName() + "Type"))
							.getMethod("setValue", Object.class).invoke(null, val));
				}
			}

		} catch (Exception ex) {
			LogOperator.info(LOGGER_NAME,
					"Set cell value [" + row.getRowNum() + "," + column + "] error: " + ex.toString());
			cell.setCellValue(val.toString());
		}
		cell.setCellStyle(style);
		return cell;
	}

	/**
	 * 添加数据（通过annotation.ExportField添加数据）
	 * 
	 * @return list 数据列表
	 */
	public <E> ExportExcel setDataList(List<E> list) {
		for (E e : list) {
			int colunm = 0;
			Row row = this.addRow();
			StringBuilder sb = new StringBuilder();
			for (Object[] os : annotationList) {
				ExcelField ef = (ExcelField) os[0];
				Object val = null;
				// Get entity value
				try {
					if (StringUtils.isNotBlank(ef.value())) {
						// if(ef.value().equals("bKnowledge.needAssign")){
						// System.out.println(ef);
						// }
						val = Reflections.invokeGetter(e, ef.value());
					} else {
						if (os[1] instanceof Field) {
							val = Reflections.invokeGetter(e, ((Field) os[1]).getName());
						} else if (os[1] instanceof Method) {
							val = Reflections.invokeMethod(e, ((Method) os[1]).getName(), new Class[] {},
									new Object[] {});
						}
					}
				} catch (Exception ex) {
					// Failure to ignore
					LogOperator.info(LOGGER_NAME, ex.toString());
					val = "";
				}

				Convertor convertor = convertorMap.get(ef);
				if (convertor != null) {
					val = convertor.convert4Export(val, e);
				}

				Map<Integer, String> enums = enumMap.get(ef);
				String decimalFormat = decimalFormatMap.get(ef);
				this.addCell(row, colunm++, val, ef.align(), ef.fieldType(), enums ,decimalFormat);
				if ((val instanceof String) && val.toString().contains("\r\n")) {
					// 单元格格式，自动换行
					String[] a = val.toString().split("\n");
					int len = 0;
					for (String s : a) {
						if (s.getBytes().length > len)
							len = s.getBytes().length;
					}
					sheet.setColumnWidth(colunm - 1, len * 256 * 2);
				}

				sb.append(val + ", ");
			}
			LogOperator.debug(LOGGER_NAME, "Write success: [" + row.getRowNum() + "] " + sb.toString());
		}
		return this;
	}

	/**
	 * @param title
	 *            表格标题，传“空值”，表示无标题
	 * @param excelField4MapList
	 *            ExcelField4Map对象list，通过annotation.ExportField获取标题
	 * @param type
	 *            导出类型（1:导出数据；2：导出模板）
	 * @param sheetName
	 *            sheet名称 add by zhuhuayan For Fault Export
	 */
	public ExportExcel(String title, List<ExcelField4Map> excelField4MapList, List<Map<String, Object>> list, String sheetName) {
		for (ExcelField4Map excelField4Map:excelField4MapList) {
			this.excelField4MapMap.put(excelField4Map.getMapKey(), excelField4Map);
		}
		if (list == null || list.isEmpty()) {
			this.excelField4MapList.addAll(excelField4MapList);
		} else {
			Map<String, Object> recordMap = list.get(0);
			for (String key : recordMap.keySet()) {
				ExcelField4Map excelField4Map = this.excelField4MapMap.get(key);
				if (excelField4Map == null) {
					continue;
				}
				this.excelField4MapList.add(excelField4Map);
			}
		}
		Collections.sort(this.excelField4MapList, Comparator.comparing(ExcelField4Map::getSort));
		this.headerList = new ArrayList<>();
		for (ExcelField4Map excelField4Map : this.excelField4MapList) {
			this.headerList.add(excelField4Map.getTitle());
		}
		initialize(title, this.headerList, sheetName);
	}

	/**
	 * 添加数据（通过annotation.ExportField添加数据）
	 *
	 * @return list 数据列表
	 */
	public ExportExcel setMapDataList(List<Map<String, Object>> list) {
		for (Map<String, Object> recordMap : list) {
			int column = 0;
			Row row = this.addRow();
			StringBuilder sb = new StringBuilder();
			for (ExcelField4Map excelField4Map : this.excelField4MapList) {
				Object val = recordMap.get(excelField4Map.getMapKey());
				this.addCell(row, column++, val, excelField4Map.getAlign().getValue(), null, null ,excelField4Map.getDecimalFormat());
				if (val != null && (val instanceof String) && val.toString().contains("\r\n")) {
					// 单元格格式，自动换行
					String[] a = val.toString().split("\n");
					int len = 0;
					for (String s : a) {
						if (s.getBytes().length > len)
							len = s.getBytes().length;
					}
					sheet.setColumnWidth(column - 1, len * 256 * 2);
				}
				sb.append(val + ", ");
			}
			LogOperator.debug(LOGGER_NAME, "Write success: [" + row.getRowNum() + "] " + sb.toString());
		}
		return this;
	}

	/**
	 * 输出数据流
	 * 
	 * @param os
	 *            输出数据流
	 */
	public ExportExcel write(OutputStream os) throws IOException {
		wb.write(os);
		return this;
	}

	/**
	 * 
	 * 输出到客户端
	 * 
	 * @param fileName
	 *            输出文件名
	 */
	public ExportExcel write(HttpServletResponse response, String fileName) throws IOException {
		response.reset();
		response.setContentType("application/octet-stream; charset=utf-8");
		response.setHeader("Content-Disposition", "attachment; filename=" + Encodes.urlEncode(fileName));
		write(response.getOutputStream());
		return this;
	}

	/**
	 * 
	 * 输出到客户端。解决firfox乱码
	 * 
	 * @param fileName
	 *            输出文件名
	 */
	public ExportExcel write(HttpServletRequest request, HttpServletResponse response, String fileName)
			throws IOException {
		response.reset();
		String userAgent = request.getHeader("User-Agent");
		if (userAgent.contains("Firefox")) {
			fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
			write(response.getOutputStream());
			return this;
		} else {
			return write(response, fileName);
		}
	}

	/**
	 * 输出到客户端
	 * 
	 * @param fileName
	 *            输出文件名
	 */
	public ExportExcel write(HttpServletResponse response, String fileName, String charset) throws IOException {
		response.reset();
		response.setContentType("application/octet-stream; charset=utf-8");
		response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
		write(response.getOutputStream());
		return this;
	}

	/**
	 * 输出到文件
	 * 
	 * @param fileName
	 *            输出文件名
	 */
	public ExportExcel writeFile(String name) throws FileNotFoundException, IOException {
		FileOutputStream os = new FileOutputStream(name);
		this.write(os);
		return this;
	}

	public ExportExcel() {
	}

	public void write2Clint(HttpServletRequest request, HttpServletResponse response, File file) throws IOException {
		response.reset();
		String userAgent = request.getHeader("User-Agent");
		if (userAgent.contains("Firefox")) {
			String fileName = new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
		} else {
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition", "attachment; filename=" + Encodes.urlEncode(file.getName()));
		}
		OutputStream out = response.getOutputStream();
		FileInputStream in = new FileInputStream(file);
		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) > 0) {
			out.write(buf, 0, len);
		}
		in.close();
	}

	/**
	 * 清理临时文件
	 * 
	 */
	public ExportExcel dispose() {
		wb.dispose();
		return this;
	}

	public String getDatePattern() {
		return datePattern;
	}

	public void setDatePattern(String datePattern) {
		this.datePattern = datePattern;
	}
}
